package gui;

import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseWheelEvent;
import java.awt.event.MouseWheelListener;
import java.util.Observable;
import java.util.Observer;

import javax.swing.JPanel;

import modele.Modele;
import Controleur.Controleur;
import Events.TranslateEvent;
import Events.ZoomEvent;

public  abstract class AbstractVue extends JPanel implements Observer {

	/**
	 * 
	 */
	private static final long serialVersionUID = -8085063712516952392L;
	
	protected Controleur controleur = new Controleur(); 
	public Modele modele = controleur.getModele();
	public Image image = null;
	
	private int mouseX, mouseY;
	
	public Controleur getControleur(){
		return controleur;
	}
	
	@Override
	public void update(Observable arg0, Object arg1) {

		image = modele.getZoomedImage();
		
		repaint();
		
	}
	
	public void paintComponent(Graphics g){

    	int x=0;
    	int y=0;
    	
    	x = modele.getImageX();
    	y = modele.getImageY();
    	
    	g.clearRect(0,0, getWidth(), getHeight());
    	
    	g.drawImage(image, x, y, this);
	        
	} 

	public int getMouseX() {
		return mouseX;
	}

	public int getMouseY() {
		return mouseY;
	}

	public AbstractVue(){

		modele.addObserver(this);
		addMouseListener(new EcouteurSouris());
		addMouseWheelListener(new WheelListener());
	}
	
	public void sendTranslationEvent(int x, int y){
		controleur.executeEvent(new TranslateEvent(x, y, modele));
	}
	
	public class WheelListener implements MouseWheelListener{

		private static final int WHEEL_ZOOM_INTERVAL = 1;

		@Override
		public void mouseWheelMoved(MouseWheelEvent e) {
			if(e.getWheelRotation() > 0){
				controleur.executeEvent(new ZoomEvent(modele.getImageZoom() - WHEEL_ZOOM_INTERVAL, modele));
			}else
				controleur.executeEvent(new ZoomEvent(modele.getImageZoom() + WHEEL_ZOOM_INTERVAL, modele));

		}
		
	}

	public class EcouteurSouris implements MouseListener{

		int startX, startY;
		
		@Override
		public void mouseReleased(MouseEvent e) {

			sendTranslationEvent(e.getX()  - startX, e.getY() - startY);

		}

		@Override
		public void mousePressed(MouseEvent e) {
			
			startX = e.getX();
			startY = e.getY();
			
		}

		@Override
		public void mouseExited(MouseEvent e) {
			// TODO Auto-generated method stub

		}

		@Override
		public void mouseEntered(MouseEvent e) {
			// TODO Auto-generated method stub

		}

		@Override
		public void mouseClicked(MouseEvent e) {
	

		}

	}
}
